<%--@elvariable id="total" type=""--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="org.example.dao.CartDAO" %>
<%@ page import="org.example.model.CartItem" %>
<%@ page import="java.util.List" %>

<%
    // 获取当前登录用户ID
    Integer userId = (Integer) session.getAttribute("userId");
    List<CartItem> cartItems = null;
    
    if (userId != null) {
        CartDAO cartDAO = new CartDAO();
        cartItems = cartDAO.getCartItems(userId);
        request.setAttribute("cartItems", cartItems);
    }
%>

<!DOCTYPE html>
<html>
<head>
    <title>淘乐乐 - 购物车</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }
        
        .header {
            background-color: #ff4d4f;
            color: white;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .container {
            max-width: 1200px;
            margin: 20px auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .cart-header {
            display: grid;
            grid-template-columns: 40px 1fr 150px 150px 150px 150px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            margin-bottom: 10px;
            font-weight: bold;
        }
        
        .cart-item {
            display: grid;
            grid-template-columns: 40px 1fr 150px 150px 150px 150px;
            padding: 15px;
            border-bottom: 1px solid #eee;
            align-items: center;
        }
        
        .product-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .product-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
        }
        
        .quantity-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .quantity-btn {
            width: 30px;
            height: 30px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        
        .quantity-input {
            width: 50px;
            height: 30px;
            text-align: center;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .cart-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 4px;
            position: sticky;
            bottom: 0;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }
        
        .total-price {
            font-size: 20px;
            color: #ff4d4f;
            font-weight: bold;
            margin-left: 5px;
        }
        
        .checkout-btn {
            padding: 12px 30px;
            min-width: 120px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        
        .checkout-btn:hover {
            background-color: #ff6b6b;
        }
        
        .delete-btn {
            color: #ff4d4f;
            cursor: pointer;
        }
        
        .empty-cart {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .empty-cart i {
            font-size: 48px;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .continue-shopping {
            color: #ff4d4f;
            text-decoration: none;
            margin-top: 20px;
            display: inline-block;
        }
        
        .cart-total {
            display: flex;
            align-items: center;
        }
        
        #discountPrice {
            color: #999;
            font-size: 14px;
        }
    </style>
    <div class="top-bar">
        <div class="container">
            <div class="nav-content">
                <div class="nav-links">
                    <c:choose>
                        <c:when test="${not empty sessionScope.userId}">
                            <span>欢迎，${sessionScope.username}</span>
                            <a href="logout">退出登录</a>
                        </c:when>
                        <c:otherwise>
                            <a href="login.jsp">请登录</a>
                            <a href="register.jsp">免费注册</a>
                        </c:otherwise>
                    </c:choose>
                </div>
            </div>
        </div>
    </div>
</head>
<body>
    <div class="header">
        <div style="font-size: 24px;">淘乐乐</div>
        <div>购物车</div>
    </div>
    
    <div class="container">
        <div class="cart-header">
            <div><input type="checkbox" id="selectAll"></div>
            <div>商品信息</div>
            <div>单价</div>
            <div>数量</div>
            <div>小计</div>
            <div>操作</div>
        </div>
        
        <!-- 购物车商品列表 -->
        <c:forEach var="item" items="${cartItems}">
            <div class="cart-item" data-product-id="${item.productId}" data-cart-id="${item.cartId}">
                <div><input type="checkbox" class="item-checkbox" checked></div>
                <div class="product-info">
                    <img src="${pageContext.request.contextPath}/images/${item.product.image}" 
                         alt="${item.product.name}" class="product-image">
                    <div>
                        <div>${item.product.name}</div>
                    </div>
                </div>
                <div class="unit-price">¥${item.product.price}</div>
                <div class="quantity-control">
                    <button class="quantity-btn minus-btn">-</button>
                    <input type="number" class="quantity-input" value="${item.quantity}" 
                         min="1" max="${item.product.stock}">
                    <button class="quantity-btn plus-btn">+</button>
                </div>
                <div class="total-price">¥${String.format("%.2f", item.product.price * item.quantity)}</div>
                <div>
                    <i class="fas fa-trash delete-btn" data-cart-id="${item.cartId}"></i>
                </div>
            </div>
        </c:forEach>
        
        <!-- 购物车为空时显示 -->
        <c:if test="${empty cartItems}">
            <div class="empty-cart">
                <i class="fas fa-shopping-cart"></i>
                <h3>购物车还是空的</h3>
                <p>快去挑选心仪的商品吧~</p>
                <a href="taolele-mall.jsp" class="continue-shopping">继续购物</a>
            </div>
        </c:if>
        
        <!-- 购物车底部 -->
        <c:if test="${not empty cartItems}">
            <div class="cart-footer">
                <div>
                    <input type="checkbox" id="selectAllBottom"> 全选
                    <span style="margin-left: 20px;">已选择 <span id="selectedCount">0</span> 件商品</span>
                </div>
                <div class="cart-total">
                    <div style="display: inline-block; text-align: right; margin-right: 20px;">
                        <div>
                            <span>合计：</span>
                            <span id="totalPrice">¥0.00</span>
                        </div>
                        <div style="font-size: 12px; color: #999;">
                            已优惠<span id="discountPrice">¥0.00</span>
                        </div>
                    </div>
                    <button class="checkout-btn" id="checkoutBtn">结算</button>
                </div>
            </div>
        </c:if>
    </div>

    <script>
        // 全选功能
        const selectAllCheckboxes = document.querySelectorAll('#selectAll, #selectAllBottom');
        const itemCheckboxes = document.querySelectorAll('.item-checkbox');
        
        // 单个商品选择状态变化
        itemCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                updateTotalPrice();
                // 检查是否需要更新全选状态
                const allChecked = Array.from(itemCheckboxes).every(item => item.checked);
                selectAllCheckboxes.forEach(box => box.checked = allChecked);
            });
        });
        
        selectAllCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const isChecked = this.checked;
                itemCheckboxes.forEach(item => item.checked = isChecked);
                selectAllCheckboxes.forEach(box => box.checked = isChecked);
                updateTotalPrice();
            });
        });
        
        // 数量加减功能
        document.querySelectorAll('.quantity-control').forEach(control => {
            const input = control.querySelector('.quantity-input');
            const minusBtn = control.querySelector('.minus-btn');
            const plusBtn = control.querySelector('.plus-btn');
            const cartItem = control.closest('.cart-item');
            const cartId = cartItem.dataset.cartId;
            
            minusBtn.addEventListener('click', () => {
                let value = parseInt(input.value);
                if (value > 1) {
                    value--;
                    input.value = value;
                    // 先更新数据库
                    updateCartQuantity(cartId, value, () => {
                        // 成功后更新UI
                        updateItemPrice(cartItem);
                    });
                }
            });
            
            plusBtn.addEventListener('click', () => {
                let value = parseInt(input.value);
                const maxStock = parseInt(input.getAttribute('max'));
                if (isNaN(value) || isNaN(maxStock)) {
                    console.error('无效的数值:', { value, maxStock });
                    return;
                }
                if (value < maxStock) {
                    value++;
                    input.value = value;
                    // 先更新数据库
                    updateCartQuantity(cartId, value, () => {
                        // 成功后更新UI
                        updateItemPrice(cartItem);
                    });
                } else {
                    alert('已达到最大库存量！');
                }
            });
            
            input.addEventListener('change', () => {
                let value = parseInt(input.value);
                const maxStock = parseInt(input.getAttribute('max'));
                if (value < 1 || isNaN(value)) {
                    value = 1;
                    input.value = 1;
                } else if (value > maxStock) {
                    value = maxStock;
                    input.value = maxStock;
                    alert('超过最大库存量');
                }
                updateItemPrice(cartItem);
                updateCartQuantity(cartId, value);
            });
        });
        
        // 更新商品价格
        function updateItemPrice(cartItem) {
            try {
                // 获取单价，移除¥符号并转换为数字
                let unitPriceText = cartItem.querySelector('.unit-price').textContent;
                if (!unitPriceText) {
                    console.error('找到单价文本');
                    return;
                }
                console.log('单价文本:', unitPriceText);
                const unitPrice = parseFloat(unitPriceText.replace('¥', ''));
                console.log('解析后的单价:', unitPrice);
                
                // 获取数量
                const quantity = parseInt(cartItem.querySelector('.quantity-input').value);
                if (isNaN(quantity)) {
                    console.error('数量解析错误');
                    return;
                }
                console.log('数量:', quantity);
                
                // 计算小计金额
                const total = unitPrice * quantity;
                console.log('计算的小计:', total);
                
                // 更新小计金额
                const totalPriceElement = cartItem.querySelector('.total-price');
                if (totalPriceElement) {
                    const formattedTotal = "¥" + "" + Math.round(total * 100) / 100;
                    totalPriceElement.innerHTML = formattedTotal;
                    console.log('设置小计显示为:', formattedTotal);
                    console.log('更新后的小计显示:', totalPriceElement.textContent);
                }
                
                updateTotalPrice();
            } catch (error) {
                console.error('更新商品价格时出错:', error);
                console.error('错误详情:', error.stack);
            }
        }
        
        // 更新购物车数量
        function updateCartQuantity(cartId, newValue, callback) {
            // 参数验证
            if (!cartId || !newValue || newValue < 1) {
                console.error('无效的参数:', { cartId, newValue });
                return;
            }

            fetch('cart/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json'
                },
                body: 'cartId=' + encodeURIComponent(cartId) + '&quantity=' + encodeURIComponent(newValue)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 数据库更新成功后执行回调
                    if (typeof callback === 'function') {
                        callback();
                    }
                } else {
                    throw new Error(data.message || '更新失败');
                }
            })
            .catch(error => {
                console.error('更新购物车失败:', error);
                alert(error.message || '更新购物车失败，请重试');
                // 恢复原来的数量并更新显示
                const cartItem = document.querySelector(`[data-cart-id="${cartId}"]`);
                if (cartItem) {
                    const input = cartItem.querySelector('.quantity-input');
                    const originalValue = input.defaultValue;
                    input.value = originalValue;
                    updateItemPrice(cartItem);
                }
            });
        }
        
        // 更新总价
        function updateTotalPrice() {
            try {
                let total = 0;
                let count = 0;
                
                const items = document.querySelectorAll('.cart-item');
                console.log('找到购物车项数量:', items.length);
                
                items.forEach((item, index) => {
                    const checkbox = item.querySelector('.item-checkbox');
                    if (checkbox && checkbox.checked) {
                        count++;
                        // 获取单价和数���重新计算
                        const unitPrice = parseFloat(item.querySelector('.unit-price').textContent.replace('¥', ''));
                        const quantity = parseInt(item.querySelector('.quantity-input').value);
                        const itemTotal = unitPrice * quantity;
                        console.log(`商品${index + 1}计算:`, { 
                            unitPrice, 
                            quantity, 
                            itemTotal,
                            unitPriceText: item.querySelector('.unit-price').textContent,
                            quantityValue: item.querySelector('.quantity-input').value
                        });
                        total += itemTotal;
                    }
                });
                
                console.log('总计:', total);
                
                // 更新合计金额显示
                const totalPriceElement = document.getElementById('totalPrice');
                if (totalPriceElement) {
                    totalPriceElement.textContent = "¥" + Math.round(total * 100) / 100;
                    console.log('设置合计显示为:', totalPriceElement.textContent);
                }
                
                // 计算优惠金额（假设优惠10%）
                const discount = total * 0.1;
                const discountElement = document.getElementById('discountPrice');
                if (discountElement) {
                    discountElement.textContent = "¥"+Math.round(discount * 100) / 100;
                    console.log('设置优惠金额显示为:', discountElement.textContent);
                }
                
                // 更新选中商品数量
                const selectedCountElement = document.getElementById('selectedCount');
                if (selectedCountElement) {
                    selectedCountElement.textContent = count;
                    console.log('设置选中数量为:', count);
                }
            } catch (error) {
                console.error('更新总价时出错:', error);
                console.error('错误详情:', error.stack);
            }
        }
        
        // 删除商品
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                if (confirm('确定要删除这个商品吗？')) {
                    const cartId = this.getAttribute('data-cart-id');
                    
                    if (!cartId) {
                        console.error('未找到购物车项ID');
                        return;
                    }
                    
                    const cartItem = this.closest('.cart-item');
                    fetch('cart/remove', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'Accept': 'application/json'
                        },
                        body: 'cartId=' + encodeURIComponent(cartId)
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应错误');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            // 移除当前商品项
                            cartItem.remove();
                            // 检查购物车是否为空
                            checkEmptyCart();
                            // 更新总价
                            updateTotalPrice();
                            console.log('商品删除成功');
                        } else {
                            throw new Error(data.message || '删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('删除商品失���:', error);
                        alert(error.message || '删除商品失败，请重试');
                    });
                }
            });
        });
        
        // 检查购物车是否为空
        function checkEmptyCart() {
            const items = document.querySelectorAll('.cart-item');
            const emptyCart = document.querySelector('.empty-cart');
            const cartFooter = document.querySelector('.cart-footer');
            
            if (!emptyCart || !cartFooter) {
                return;
            }
            
            if (items.length === 0) {
                emptyCart.style.display = 'block';
                cartFooter.style.display = 'none';
                // 延迟刷新页面，让用户看到删除效果
                setTimeout(() => {
                    window.location.reload();
                }, 500);
            }
        }
        
        // 结算功能
        function checkout() {
            try {
                const selectedItems = document.querySelectorAll('.item-checkbox:checked');
                if (selectedItems.length === 0) {
                    alert('请选择要购买的商品');
                    return;
                }

                // 获取合计金额（已包含优惠）
                const totalAmount = parseFloat(document.getElementById('totalPrice').textContent.replace('¥', ''));
                
                // 获取优惠金额
                const discountAmount = parseFloat(document.getElementById('discountPrice').textContent.replace('¥', ''));

                console.log('结算金额:', totalAmount);
                console.log('优惠金额:', discountAmount);

                // 收集选中的商品ID和数量
                const items = Array.from(selectedItems).map(checkbox => {
                    const cartItem = checkbox.closest('.cart-item');
                    const productName = cartItem.querySelector('.product-info div div').textContent;
                    const productImage = cartItem.querySelector('.product-image').src.split('/').pop();
                    return {
                        cartId: cartItem.dataset.cartId,
                        productId: cartItem.dataset.productId,
                        quantity: cartItem.querySelector('.quantity-input').value,
                        price: parseFloat(cartItem.querySelector('.unit-price').textContent.replace('¥', '')),
                        subtotal: parseFloat(cartItem.querySelector('.total-price').textContent.replace('¥', '')),
                        name: productName,
                        image: productImage
                    };
                });

                console.log('选中的商品:', items);

                // 将选中的商品信息转换为查询字符串
                const itemsParam = encodeURIComponent(JSON.stringify(items));

                // 构建支付页面URL，包含所有必要信息
                const paymentUrl = new URL('payment.jsp', window.location.href);
                paymentUrl.searchParams.set('amount', totalAmount.toFixed(2));
                paymentUrl.searchParams.set('discount', discountAmount.toFixed(2));
                paymentUrl.searchParams.set('items', itemsParam);
                paymentUrl.searchParams.set('itemCount', selectedItems.length);

                console.log('跳转URL:', paymentUrl.toString());
                console.log('商品数据:', itemsParam);

                // 跳转到支付页面
                window.location.href = paymentUrl.toString();
            } catch (error) {
                console.error('结算过程中出错:', error);
                alert('结算失败，请重试');
            }
        }
        
        // 初始化
        function initializeCart() {
            try {
                console.log('开始初始化购物车...');
                
                // 检查购物车项
                const cartItems = document.querySelectorAll('.cart-item');
                console.log('找到购物车项数量:', cartItems.length);
                
                // 先更新所有商品的小计
                cartItems.forEach((cartItem, index) => {
                    console.log(`正在计算第${index + 1}个商品的小计...`);
                    updateItemPrice(cartItem);
                });
                
                // 确保所有商品都被选中
                document.querySelectorAll('.item-checkbox').forEach(checkbox => {
                    checkbox.checked = true;
                });
                
                // 更新总价
                updateTotalPrice();
                
                // 设置全选
                const selectAllCheckboxes = document.querySelectorAll('#selectAll, #selectAllBottom');
                selectAllCheckboxes.forEach(checkbox => {
                    checkbox.checked = true;
                });
                
                // 绑定结算按钮事件
                const checkoutBtn = document.getElementById('checkoutBtn');
                if (checkoutBtn) {
                    checkoutBtn.addEventListener('click', function() {
                        checkout();
                    });
                }
                
                console.log('购物车初始化完成');
            } catch (error) {
                console.error('初始化购物车时出错:', error);
            }
        }
        
        // 确保DOM完全加载后再初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM加载完成开始初始化...');
            initializeCart();
        });
    </script>
</body>
</html> 